import routers from './router';

export default {
  // 页面跳转
  push: function(options) {
    let query = '';
    for (let prop in options.params) {
      if (options.params.hasOwnProperty(prop)) {
        query += `${prop}=${options.params[prop]}&`;
      }
    }
    // 去除末尾的&
    if (query.endsWith('&')) {
      query = query.slice(0, query.length - 1);
    }
    
    const _url = !routers[options.url] ? options.url : routers[options.url]
    uni.navigateTo({
      url: `${_url}?${query}`,
      fail: (err)=> {
        console.log('🚀参数错误/路径错误，请仔细检查!🚀',_url);
      }
    });
  },
 
  // 关闭当前页面，跳转到应用内的某个页面
  replace: function(options) {
    let query = '';
    for (let prop in options.params) {
      if (options.params.hasOwnProperty(prop)) {
        query += `${prop}=${options.params[prop]}&`;
      }
    }
    if (query.endsWith('&')) {
      console.log('query',query);
      query = query.slice(0, query.length - 1);
      console.log('query',query);
    }
    
    const _url = !routers[options.url] ? options.url : routers[options.url]
    uni.redirectTo({
      url: `${_url}?${query}`,
      fail: (err)=> {
        console.log('🚀参数错误/路径错误，请仔细检查!🚀',_url);
      }
    });
  }, 
  // 关闭所有页面，打开到应用内的某个页面
  launch: function(options) {
    let query = '';
    for (let prop in options.params) {
      if (options.params.hasOwnProperty(prop)) {
        query += `${prop}=${options.params[prop]}&`;
      }
    }
    if (query.endsWith('&')) {
      query = query.slice(0, query.length - 1)
    }

    const _url = !routers[options.url] ? options.url : routers[options.url]
    uni.reLaunch({
      url: `${_url}?${query}`,
      fail: (err)=> {
        console.log('🚀参数错误/路径错误，请仔细检查!🚀',_url);
      }
    });
  },
 
  // 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
  switch: function(options) {
    let query = '';
    for (let prop in options.params) {
      if (options.params.hasOwnProperty(prop)) {
        query += `${prop}=${options.params[prop]}&`;
      }
    }
    if (query.endsWith('&')) {
      query = query.slice(0, query.length - 1);
    }

    const _url = !routers[options.url] ? options.url : routers[options.url]
    uni.switchTab({
      url: `${_url}?${query}`,
      fail: (err)=> {
        console.log('🚀参数错误/路径错误，请仔细检查!🚀',_url);
      }
    });
  },
  
  // 返回上一级
  back: function(num) {
    uni.navigateBack({
      delta: num ? num :1
    })
  }

};